package com.carkeeper.web.filter;

import com.carkeeper.web.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthService authService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public  static final String LOGIN_URL="http://localhost:8001/api/oauth/toLogin";


    /**
     * 1）判断当前请求是否为登录请求，是的话，则放行
     * 2) 判断cookie中是否存在信息, 没有的话，拒绝访问
     * 3）判断redis中令牌是否存在，没有的话，拒绝访问
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.判断当前请求是否为登录请求
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();

        //2判断请求路径中是否包含登录请求
        if (path != null && path.contains("/api/oauth/login") || path.contains("/v2/api-docs") ||path.contains("/api/oauth/toLogin") || !UrlFilter.hasAuthorize(request.getURI().getPath())){

            return chain.filter(exchange);
        }

        //3否则，判断cookie中是否存在信息，没有的话，拒绝访问
        String jti = authService.getJtiFromCookie(request);

        //没有则拒绝访问
        if (!StringUtils.isNotEmpty(jti)){
            /*response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();*/
           return toLoginPage(LOGIN_URL+"?FROM="+path,exchange);
        }

        //4.判断redis中令牌是否存在，没有的话，拒绝访问
        String token = redisTemplate.boundValueOps(jti).get();
        if (token == null){
           /* response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();*/
            return toLoginPage(LOGIN_URL+"?FROM="+path,exchange);
        }

        //5.校验通过，请求头增强，放行
        request.mutate().header("Authorization","Bearer "+token);
        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }

    public Mono<Void> toLoginPage(String loginUrl, ServerWebExchange exchange){

        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location",loginUrl);
        return  response.setComplete();
    }
}
